﻿<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="../helpproject.xsl" ?>
<topic template="Default" lasteditedby="Geert" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../helpproject.xsd">
  <title translate="true">How can I inject or manipulate the view model of a UserControl?</title>
  <keywords>
    <keyword translate="true">FAQ</keyword>
    <keyword translate="true">Injecting view models</keyword>
    <keyword translate="true">UserControl&lt;TViewModel&gt;</keyword>
  </keywords>
  <body>
    <header>
      <para styleclass="Heading1"><text styleclass="Heading1" translate="true">How can I inject or manipulate the view model of a UserControl?</text></para>
    </header>
    <para styleclass="Normal"><text styleclass="Normal" translate="true">The </text><link displaytype="text" defaultstyle="true" type="topiclink" href="T_Catel_Windows_Controls_UserControl" styleclass="Normal" translate="true">UserControl</link><text styleclass="Normal" translate="true"> is a very powerful control. It allows lazy loaded dynamic view model construction. However, sometimes you just don&apos;t want the user control to dynamically create the view model. Luckily, the user control instantiates a new view model with this logic:</text></para>
    <list id="1" type="ol" listtype="decimal" formatstring="&#37;&#48;&#58;&#115;&#46;" format-charset="DEFAULT_CHARSET" levelreset="true" legalstyle="false" startfrom="1" styleclass="Normal (list)" style="font-family:Arial; font-size:10pt; color:#000000;">
      <li styleclass="Normal (list)"><text styleclass="Normal (list)" translate="true">The DataContext of the control can be injected into a constructor of the view model</text></li>
      <li styleclass="Normal (list)"><text styleclass="Normal (list)" translate="true">The view model has an empty constructor</text></li>
    </list>
    <para styleclass="Normal"><text styleclass="Normal" translate="true">You can set the </text><text styleclass="Normal" style="font-style:italic;" translate="true">DataContext</text><text styleclass="Normal" translate="true"> of the control to a view model, and this way &quot;inject&quot; a view model into a control instead of letting it be created first. In fact, the user control first checks whether the </text><text styleclass="Normal" style="font-style:italic;" translate="true">DataContext</text><text styleclass="Normal" translate="true"> is already a valid view model for the user control. If so, it keeps it that way.</text></para>
  </body>
</topic>
